<template>
  <!--账号管理-->
  <div class="user-admin">
    <div class="user-admin-header-seach">
      <el-input
        v-model="userName"
        style="width: 240px"
        placeholder="请输入账号名称或手机号"
      />
      <div class="header-seach-item">
        <span>所属机构：</span>
        <el-select v-model="userOrg" style="width: 240px">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in orgList"
            :key="item.id"
            :label="item.orgName"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="header-seach-item">
        <span>用户角色：</span>
        <el-select v-model="userRole" style="width: 140px">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in userRoleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="header-seach-item">
        <span>用户状态：</span>
        <el-select v-model="userState" style="width: 140px">
          <el-option label="全部" :value="-1" />
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </div>
      <el-button @click="reset">重置</el-button>
      <el-button
        color="rgb(222, 41, 16)"
        type="primary"
        style="margin-left: -10px"
        @click="getUserList"
        >查询</el-button
      >
    </div>
    <el-divider />
    <div class="user-admin-header">
      <div class="header-tip">
        总计 <span class="header-tip-nember">{{ userList?.total }}</span> 个账号
      </div>
      <div class="header-tip-botton">
        <el-button
          color="rgb(222, 41, 16)"
          type="primary"
          @click="adduser"
          v-if="permissionState.update"
          ><el-icon><Plus /></el-icon>新增账号</el-button
        >
        <el-button color="rgb(222, 41, 16)" type="primary">导出excel</el-button>
      </div>
    </div>
    <div class="user-admin-table">
      <el-table
        :data="userList?.list"
        stripe
        border
        style="width: 98%"
        :header-cell-style="tableHeaderColor"
        :cell-style="cellStyle"
        max-height="60vh"
      >
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="name" label="账号名" width="180" />
        <el-table-column prop="phone" label="手机号" width="180" />
        <el-table-column prop="orgName" label="机构" width="180" />
        <el-table-column prop="role" label="角色" width="180" />
        <el-table-column prop="state" label="状态" width="180">
          <template #default="scoped">
            <span
              style="color: rgb(0, 128, 255); margin-right: 10px"
              v-if="scoped.row.stateb"
              >有效</span
            >
            <span
              style="color: rgb(219, 0, 64); margin-right: 10px"
              v-if="!scoped.row.stateb"
              >无效</span
            >
            <el-switch
              v-model="scoped.row.stateb"
              class="mb-2"
              size="small"
              style="
                --el-switch-on-color: rgb(0, 128, 255);
                --el-switch-off-color: #ff4949;
              "
              @change="
                changeUserState(scoped.row.id, scoped.row.stateb ? 1 : 0)
              "
            />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column
          fixed="right"
          label="操作"
          min-width="120"
          v-if="permissionState.update || permissionState.delete"
        >
          <template #default="scoped">
            <el-button
              link
              type="primary"
              size="small"
              @click="edituser(scoped.row.id)"
              v-if="permissionState.update"
            >
              <span style="color: rgb(222, 41, 16)">编辑</span></el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              v-if="permissionState.delete"
              ><span style="color: #ff4949" @click="deleteUser(scoped.row.id)">
                <span style="color: rgb(222, 41, 16)">删除</span></span
              ></el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="user-admin-pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="userList?.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { useRouter } from "vue-router"; // 引入useRouter函数
import { Permission } from "@/util/LocalStorgeGetPermission";
import http from "@/request/request";
import { Data } from "@/request/pageData";

const router = useRouter(); // 获取路由实例
interface User {
  id: number;
  name: string;
  phone: string;
  state: number;
  role: string;
  createdAt: string;
  stateb: boolean;
}
interface Role {
  id: number;
  roleName: string;
}

interface Org {
  id: number;
  orgName: string;
}
//---------------------------------变量----------------------------------//
// table样式
const tableHeaderColor = {
  background: "rgb(245, 248, 250) !important",
  color: "rgb(51, 51, 51)",
  "text-align": "center",
};
const cellStyle = {
  "text-align": "center",
};
const userList = ref<Data<User>>();
const currentPage = ref(1);
const pageSize = ref(10);

const userName = ref<string>("");
const userOrg = ref(0);
// 机构列表
const orgList = ref<Org[]>([]);
// 用户角色列表
const userRoleList = ref<Role[]>([]);

const userRole = ref(0);
const userState = ref(-1);
const permissionState = ref({
  insert: false,
  update: false,
  delete: false,
});
//-------------------------------------方法------------------------------//
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  getUserList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  getUserList();
};
// 重置
const reset = () => {
  userName.value = "";
  userOrg.value = 0;
  userRole.value = 0;
  userState.value = -1;
};
// 编辑账号
const edituser = (id: number) => {
  console.log(id);
  router.push("/userEdit?id=" + id);
};
// 新增账号
const adduser = () => {
  router.push("/userEdit");
};
// 修改状态
const changeUserState = async (id: number, state: number) => {
  console.log(id, state);
  try {
    await http.post("/api/system/updateUserStatus", {
      id,
      state,
    });
  } catch (err) {
    console.log(err);
  }
  getUserList();
};
// 查询用户列表
const getUserList = async () => {
  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    phoneOrName: userName.value,
    orgId: userOrg.value == 0 ? null : userOrg.value,
    roleId: userRole.value == 0 ? null : userRole.value,
    state: userState.value == -1 ? null : userState.value,
  };
  try {
    const { data } = await http.get<Data<User>>(
      "/api/system/getUserListByPhoneAndNameOrOrgIdAndStatusAndRole",
      params
    );
    userList.value = data;
    userList.value.list.forEach((e) => {
      e.stateb = e.state === 1;
    });
  } catch (err) {
    console.log(err);
  }
};
// 删除用户
const deleteUser = async (id: number) => {
  try {
    await http.post("/api/system/deleteUser?userId=" + id);
    getUserList();
  } catch (err) {
    console.log(err);
  }
};

// 查询所有角色列表
const getAllRoleList = async () => {
  try {
    const { data } = await http.get<Role[]>("/api/system/getAllRoleList");
    userRoleList.value = data;
  } catch (err) {
    console.log(err);
  }
};
// 查询机构列表
const getAllOrgList = async () => {
  try {
    const { data } = await http.get<Org[]>("/api/system/getEnabledOrgList");
    orgList.value = data;
  } catch (err) {
    console.log(err);
  }
};
//-------------------------------------------------生命周期----------------------------//
onMounted(() => {
  const p = new Permission("/user").getPermission();
  if (!p) {
    router.push("/");
  } else {
    permissionState.value = p;
    getAllRoleList();
    getAllOrgList();
    getUserList();
  }
});
</script>

<style lang="less" scoped>
.user-admin {
  background-color: rgb(255, 255, 255);
  width: 97%;
  height: 96%;
  padding: 20px;
}
.user-admin-header-seach {
  display: flex;
  gap: 20px;
}
.user-admin-header {
  display: flex;
  width: 100%;

  // margin-left: 80%;
  margin-bottom: 10px;
  .header-tip {
    width: 8%;
    .header-tip-nember {
      color: rgb(64, 158, 255);
    }
  }
  .header-tip-botton {
    width: 90%;
    display: flex;
    justify-content: end;
  }
}
.user-admin-pagination {
  position: absolute;
  right: 2%;
  top: 90%;
}
</style>